package com.skyworth.demo.startactivity;

import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.util.Log;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.math.BigInteger;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;
import java.security.MessageDigest;


public class LiteUpgradeService {

    public static class MyStub implements LiteUpgradeDownloader.LiteUpgradeDownloaderListener {
        private static final String UPDATE_FILE = "update.apk";
        private static final String UPDATE_TEMP_FILE = "update.apk.tmp";

        private LiteUpgradeDownloader downloader = null;
        private Context mContext = null;
        private String save_path = null;
        private String update_file_path = null, update_temp_file_path = null;

        public MyStub(Context context) {
            mContext = context;
            downloader = new LiteUpgradeDownloader(mContext);
            downloader.setListener(this);
            save_path = context.getCacheDir().getAbsolutePath();

            File file = new File(save_path);
            file.setReadable(true, false);

            update_file_path = save_path + "/" + UPDATE_FILE;
            update_temp_file_path = save_path + "/" + UPDATE_TEMP_FILE;
        }

        public synchronized void checkUpgrade() {
            performDownload(999999999);
        }


        private int getCurrentVersionCode() {
            int versionCode = -1;
            try {
                versionCode = mContext.getPackageManager().getPackageInfo(mContext.getPackageName(), 0).versionCode;
            } catch (PackageManager.NameNotFoundException e) {
                e.printStackTrace();
                Log.e("upgrade", "getCurrentVersionCode " + e.getMessage());
            }
            return versionCode;
        }

        private int getDownloadedUpdateApkVersionCode() {
            if (new File(update_temp_file_path).exists())
                return -1;//正在下載
            if (new File(update_file_path).exists()) {
                try {
                    PackageManager pm = mContext.getPackageManager();
                    PackageInfo info = pm.getPackageArchiveInfo(update_file_path, PackageManager.GET_ACTIVITIES);
                    return info.versionCode;
                } catch (Exception e) {
                }
            }
            //沒有下載過
            return -2;
        }

        private static final String DOWNLOAD_URL =
                "http://apk.sky.fs.skysrt.com/uploads/20151126/20151126165517880514.apk";


        private void performDownload(int versionCode) {
            int current_vc = getCurrentVersionCode();
            int downloaded_vc = getDownloadedUpdateApkVersionCode();
            Log.i("upgrade", "performDownload current_vc:" + current_vc + "  downloaded_vc:" + downloaded_vc + "  info.ver:" + versionCode);
            Log.i("upgrade", "performDownload update_file_path:" + update_file_path);
            if (current_vc >= downloaded_vc && downloaded_vc > 0) {
                File file = new File(update_temp_file_path);
                if (file.exists())
                    file.delete();
                file = new File(update_file_path);
                if (file.exists())
                    file.delete();
//                kernel.onUpdateFileNotExist();
            } else if (downloaded_vc >= 0 && downloaded_vc > current_vc && downloaded_vc >= versionCode) {
//                kernel.onUpdateFilePrepared(update_file_path);
            } else {
                if (current_vc < versionCode)
                    downloader.start(update_file_path, DOWNLOAD_URL);
//                kernel.onUpdateFileNotExist();
            }
        }

        @Override
        public void onStart() {
//            kernel.onStart();
        }

        @Override
        public void onProgress(int percent, long downloaded_length, long file_length) {
//            kernel.onProgress(percent, downloaded_length, file_length);
        }

        @Override
        public void onCancel() {
//            kernel.onCancel();
        }

        @Override
        public void onError() {
//            kernel.onError();
        }

        private static final String C_MD5 = "0fede54dc6838e3a05fed957ecface89";

        @Override
        public void onSuccess() {
//            kernel.onSuccess();
//            kernel.onUpdateFilePrepared(update_file_path);


            String md5 = null;
            try {
                md5 = getMd5(new File(update_file_path));
                System.out.println(md5);
                if (!C_MD5.contains(md5)) {
                    System.out.println("!!!!!!!!!!!!!!" + update_file_path);
                    throw new RuntimeException("");
                }
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            }
        }


    }

    public static String getMd5(File file) throws FileNotFoundException {
        String value = null;
        FileInputStream in = new FileInputStream(file);
        try {
            MappedByteBuffer byteBuffer = in.getChannel().map(FileChannel.MapMode.READ_ONLY, 0, file.length());
            MessageDigest md5 = MessageDigest.getInstance("MD5");
            md5.update(byteBuffer);
            BigInteger bi = new BigInteger(1, md5.digest());
            value = bi.toString(16);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (null != in) {
                try {
                    in.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return value;
    }

    private MyStub stub = null;

    //    @Override
    public void onCreate() {

//        stub = new MyStub(this);
    }
}
